const Router = require('koa-router');
// const compiler = require('../components/webpack/index');
const webpackConfig = require('../../webpack.config');
const webpack = require('webpack');
const jsBeautify = require('../tool/jsbeautify');
const indexRoute = new Router();

const callback = (err, stats) => {
    console.log('Compiler has finished execution.');
    process.stdout.write(stats.toString() + "\n");
};

indexRoute.get('/', async(ctx, next) => {
    const queryConfig = ctx.query;
    const myWebpackConfig = Object.assign({}, webpackConfig, queryConfig);
    const compiler = webpack(myWebpackConfig);
    const status = await new Promise((resolve, reject) => {
        compiler.run((err, stats) => {
            // err && console.log('错误内容是', err);
            // !err && console.log('状态信息', stats);
            const options = stats.compilation.compiler.options;
            err && reject(JSON.stringify(err)) || resolve(jsBeautify(JSON.stringify(options)));
        });
    })
    ctx.body = status;
    await next();
});

indexRoute.get('/dashboard', async(ctx, next) => {
    await ctx.render('index.hbs', {
        title: 'hello'
    });
    console.log(ctx.websocket);
    await next();
})

function register(app) {
    app.use(indexRoute.routes());
    app.use(indexRoute.allowedMethods())
}

module.exports = register;